package com.rf.sys.exception;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.rf.sys.utils.ExceptionUtil;

/**
 * 全局异常类
 * @author dehuisun
 *
 */
@Component
public class MyExceptionHandler implements HandlerExceptionResolver {

	private static final Logger logger = Logger
			.getLogger(MyExceptionHandler.class);

	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		 ModelAndView modelAndView = new ModelAndView();
		 String errMsg=ex.getMessage();
		String exceptionMessage = ExceptionUtil.getExceptionMessage(ex);
		logger.error(exceptionMessage);
	    if (!(request.getHeader("accept").contains("application/json")  || (request.getHeader("X-Requested-With")!= null && request
	       .getHeader("X-Requested-With").contains("XMLHttpRequest") ))) {
		   
		    modelAndView.addObject("errMsg", errMsg);
			modelAndView.addObject("ex", ex);
			modelAndView.setViewName("error/error");
			return modelAndView;
	   } else {// ajax
	       try {
	    	   JSONObject returnObj = new JSONObject();
	    	   returnObj.element("httpCode", "ERROR");//失败
	    	   if(ex instanceof BusinessException){
	    		   returnObj.element("errMsg",errMsg);
	    	   }else if(ex instanceof EquipException){
	    		   returnObj.element("errMsg","设备异常,请联系稍后重试或联系管理员！");
	    	   }else{
	    		   returnObj.element("errMsg","网络异常，请联系稍后重试或联系管理员！");
	    	   }
	   		
	   		   response.setContentType("text/json; charset=utf-8");
			   response.setCharacterEncoding("UTF-8");
			   response.getWriter().print(returnObj.toString());
			   response.getWriter().close();
	       } catch (IOException e) {
	           e.printStackTrace();
	       }
	       return null;
	   }
	}
}
